﻿/*
 * 2008 (c) ralfoide at gmail com
 * Project: SharpFlow
 * License: GPL
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Alfray.SharpFlow.Core;
using Alfray.SharpFlow.Utils;

namespace Alfray.SharpFlow.UI {
    /// <summary>
    /// Form that displays the debug log.
    /// Created on demande the first time the log is displayed,
    /// then simply has its visibility toggled.
    /// </summary>
    public partial class DebugLogForm : AutoSavingForm {

        /// <summary>
        /// Private constructor.
        /// Sets up the log listener.
        /// </summary>
        public DebugLogForm() {
            InitializeComponent();

            DataCore.singleton.logListener += OnLogUpdated;
        }

        /// <summary>
        /// Called by the DataCore when the log is modified.
        /// Updates the log text box and makes sure to scroll to the bottom.
        /// This method is safe to call from worker threads.
        /// </summary>
        private void OnLogUpdated(object sender, DataCore.LogEventArgs args) {
            if (!mTextBox.InvokeRequired) {
                mTextBox.Text = args.logContent();
                mTextBox.SelectionStart = mTextBox.TextLength;
                mTextBox.ScrollToCaret();
            } else {
                // Invoke itself on the UI thread
                InvokeDelegate d = delegate() {
                    this.OnLogUpdated(sender, args);
                };
                mTextBox.Invoke(d);
            }
        }

        /// <summary>
        /// Called when the debug log is actually closed.
        /// Removes the log listener.
        /// </summary>
        private void DebugLogForm_FormClosing(object sender, FormClosingEventArgs e) {
            DataCore core = DataCore.singleton;
            DataCore.singleton.logListener -= OnLogUpdated;
        }
    }
}
